﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Mvc;
using WalkingTec.Mvvm.Core.Extensions;
using System.Linq;
using System.Collections.Generic;
using TyMES.Model.Record;
using TyMES.ViewModel.Record.MachineStatusRecordVMs;
using TyMES.Model;
using Elsa.Server.Api.Endpoints.WorkflowDefinitions;
using Newtonsoft.Json;
using TyMES.Communication;
using TyMES.Services;
using TyMES.TemporaryClass;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace TyMES.Record.Controllers
{
    [AuthorizeJwtWithCookie]
    [ActionDescription("_Model.MachineStatusRecord")]
    [ApiController]
    [Route("/api/Record/MachineStatusRecord")]
    public partial class MachineStatusRecordController : BaseApiController
    {
        private readonly IConfiguration configuration;
        private readonly HttpService httpService;
        private string factoryCode;
        private string lineCode;
        private string mesIP;
        private string mesPort;

        public MachineStatusRecordController( HttpService httpService,IConfiguration configuration)
        {           
            this.httpService = httpService;
            this.factoryCode = configuration["FactoryCode"];
            this.lineCode = configuration["LineCode"];
            this.mesIP = configuration["MESIP"];
            this.mesPort = configuration["MESPORT"];
        }

        [ActionDescription("Sys.Get")]
        [HttpGet("{id}")]
        public IActionResult Get(string id)
        {
            var vm = Wtm.CreateVM<MachineStatusRecordVM>(id);
            return Ok(vm);
        }

        [ActionDescription("Sys.Create")]
        [HttpPost("[action]")]
        public async Task<IActionResult> Create(MachineStatusRecordVM vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                await vm.DoAddAsync();
   
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }

        }

        [ActionDescription("Sys.Edit")]
        [HttpPut("[action]")]
        public async Task<IActionResult> Edit(MachineStatusRecordVM vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                await vm.DoEditAsync(false);
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }
        }
                

        [HttpPost("BatchEdit")]
        [ActionDescription("Sys.BatchEdit")]
        public ActionResult BatchEdit(MachineStatusRecordBatchVM vm)
        {
            if (!ModelState.IsValid || !vm.DoBatchEdit())
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                return Ok(vm.Ids.Count());
            }
        }

		[HttpPost("BatchDelete")]
        [ActionDescription("Sys.Delete")]
        public IActionResult BatchDelete(string[] ids)
        {
            var vm = Wtm.CreateVM<MachineStatusRecordBatchVM>();
            if (ids != null && ids.Count() > 0)
            {
                vm.Ids = ids;
            }
            else
            {
                return Ok();
            }
            if (!ModelState.IsValid || !vm.DoBatchDelete())
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                return Ok(ids.Count());
            }
        }

        [ActionDescription("Sys.DownloadTemplate")]
        [HttpGet("GetExcelTemplate")]
        public IActionResult GetExcelTemplate()
        {
            var vm = Wtm.CreateVM<MachineStatusRecordImportVM>();
            var qs = new Dictionary<string, string>();
            foreach (var item in Request.Query.Keys)
            {
                qs.Add(item, Request.Query[item]);
            }
            vm.SetParms(qs);
            var data = vm.GenerateTemplate(out string fileName);
            return File(data, "application/vnd.ms-excel", fileName);
        }

        [ActionDescription("Sys.Import")]
        [HttpPost("Import")]
        public ActionResult Import(MachineStatusRecordImportVM vm)
        {

            if (vm.ErrorListVM.EntityList.Count > 0 || !vm.BatchSaveData())
            {
                return BadRequest(vm.GetErrorJson());
            }
            else
            {
                return Ok(vm.EntityList.Count);
            }
        }

        [ActionDescription("同步设备状态")]
        [HttpPost("EquipmentStatus")]
        [NoLog]
        public async Task<ResponseBase> EquipmentStatus(MachineStatusRecord machineStatusRecord)
        {
            machineStatusRecord.FactoryCode = "TH13";

            //判断上传状态是否变动

            StationLogRecord stationLog = new StationLogRecord();
            stationLog.StationCode = machineStatusRecord.StationCode;
            stationLog.LineCode = machineStatusRecord.LineCode;
            stationLog.CreateTime = DateTime.Now;
            stationLog.Date_Time = DateTime.Now;

            EquipmentStatusUploadTable statusUploadTable = new EquipmentStatusUploadTable();
            statusUploadTable.data = new List<EquipmentStatusTable>();
            EquipmentStatusTable statusTable = new EquipmentStatusTable();

            statusTable.machineCode = machineStatusRecord.MachineCode;
            statusTable.lineCode = machineStatusRecord.LineCode;
            statusTable.stationCode = machineStatusRecord.StationCode;
            //11需要配合machineCode一起上传，目前设备号不上传，所以11改成2上传
            if (machineStatusRecord.MachineStatusCode == "11")
                machineStatusRecord.MachineStatusCode = "2";
            statusTable.machineStatusCode = machineStatusRecord.MachineStatusCode;
            statusTable.machineStatusBegin = machineStatusRecord.MachineStatusBegin;
            //statusTable.machineStatusEnd = machineStatusRecord.MachineStatusEnd;
            //statusTable.editTime = machineStatusRecord.EditTime;
            //statusTable.StatusType = machineStatusRecord.MachineStatusCode;
            //statusTable.acquisitCode = machineStatusRecord.MachineCode;//
            statusUploadTable.data.Add(statusTable);

            try
            {
                string postdata1 = JsonConvert.SerializeObject(statusUploadTable);
                string post = await httpService.PostDataAsync("http://" + mesIP + ":" + mesPort + "/api/product/Product_Information", postdata1);
                RPWResponse result = JsonConvert.DeserializeObject<RPWResponse>(post);
                if (result.code == "000000" && result.success)
                {
                    //把上传成功的数据uploadflag置true
                    machineStatusRecord.Uploadflag = true;
                    DoAddStationMachineStatusLog(machineStatusRecord);
                    stationLog.LogType = "good";
                    stationLog.Log = "设备状态上传成功"+ machineStatusRecord.MachineCode+ ":" + result.mesg;
                    DoAddStationStatusLog(stationLog);
                    return new ResponseBase(true, result.code + ":" + result.mesg);
                }
                else
                {
                    machineStatusRecord.Uploadflag = false;
                    DoAddStationMachineStatusLog(machineStatusRecord);
                    stationLog.LogType = "bad";
                    stationLog.Log = "设备状态上传失败"+ machineStatusRecord.MachineCode + ":" + result.data + ":" + result.mesg ;
                    DoAddStationStatusLog(stationLog);
                    return new ResponseBase(true, result.data + ":" + result.mesg);
                }
            }
            catch (Exception ex)
            {
                machineStatusRecord.Uploadflag = false;
                DoAddStationMachineStatusLog(machineStatusRecord);
                stationLog.LogType = "bad";
                stationLog.Log = "设备状态上传失败"+machineStatusRecord.MachineCode + ":" + ex.Message;
                DoAddStationStatusLog(stationLog);
                return new ResponseBase(true, ex.Message);
            }
        }

        public void DoAddStationStatusLog(StationLogRecord stationLog)
        {
            DC.Set<StationLogRecord>().Add(stationLog);
            DC.SaveChanges();
        }

        public void DoAddStationMachineStatusLog(MachineStatusRecord record)
        {
            DC.Set<MachineStatusRecord>().Add(record);
            DC.SaveChanges();
        }

        public class EquipmentStatusUploadTable
        {
            public string factoryCode = "TH13";
            //public string userName { get; set; }
            public string serviceId = "Product005_EquipmentStatus";
            public string requestTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            public List<EquipmentStatusTable> data { get; set; }

        }
        public class EquipmentStatusTable
        {
            public string machineCode { get; set; }
            public string lineCode { get; set; }
            public string stationCode { get; set; }
            public string machineStatusCode { get; set; }
            //public string acquisitCode { get; set; }
            public string machineStatusBegin { get; set; }
            //public string machineStatusEnd { get; set; }
            //public string editTime { get; set; }
            //public string StatusType { get; set; }

        }


    }
}